// indexedDB.js
class IndexdedDB {
  constructor(name = 'custom', version = 1) {
    this.request = null;
    this.db = null;
    this.name = name;
    this.version = version;
  }
  // 因为获取数据库是异步操作，所以用promise封装下

  getDb(key) {
    return new Promise((resolve, reject) => {
      if (this.db) {
        resolve();
        return;
      }

      // 打开数据库
      this.request = window.indexedDB.open(this.name, this.version);
      // 打开数据库的时候就应该创建对象存储
      this.request.onsuccess = (event) => { // 貌似用这个不行
        console.log('获取数据库成功');
        this.db = event.target.result;
        resolve();
      };
      // 当你创建一个新的数据库或者增加已存在的数据库的版本号
      this.request.onupgradeneeded = (event) => {
        console.log('新建数据库成功');
        this.db = event.target.result;
        this.objectStore = this.db.createObjectStore(key, { keyPath: key });
        this.objectStore.transaction.oncomplete = (event) => {
          console.log('对象存储已经存在');
        };
      };
      this.request.onerror = (event) => {
        // 针对此数据库请求的所有错误的通用错误处理器！
        console.error(`数据库错误：${event.target.errorCode}`);
        reject(new Error(`数据库错误：${event.target.errorCode}`));
      };
    });
  }

  // 新增数据, 用Key做为对象存储名字， 和keyPath
  async addData(key, data) {
    try {
      await this.getDb(key);
      const newData = {
        [key]: key,
        value: JSON.stringify(data),
      };
      // 先判断有没有在对象存储中，有的话就更新
      const res = await this.getData(key, data.typg.customerId);
      if (res) {
        this.editData(key, newData);
        return;
      }
      // 将数据保存到新创建的对象存储中。
      const customerObjectStore = this.db
        .transaction(key, 'readwrite')
        .objectStore(key);
      console.log('customerObjectStore', customerObjectStore);
      const addRequest = customerObjectStore.add(newData);
      addRequest.onsuccess = function() {
        console.log('Data added successfully:', newData);
      };
      addRequest.onerror = function(event) {
        console.log('Error adding data:', event.target.message);
      };
    } catch (error) {

    }
  }
  // 获取数据

  async getData(key, value) {
    return new Promise(async (resolve, reject) => {
      await this.getDb();
      const transaction = this.db.transaction([key]);
      const objectStore = transaction.objectStore(key);
      // 使用 get() 要求你知道你想要检索哪一个键
      const request = objectStore.get(value);
      request.onerror = (event) => {
        // 错误处理！
        reject(new Error('获取失败'));
      };
      request.onsuccess = (event) => {
        console.log('request.result', request.result);
        // 对 request.result 做些操作！
        request.result ? resolve(JSON.parse(request.result.value)) : resolve(null);
      };
    });
  }

  async editData(key, newData) {
    const objectStore = this.db
      .transaction([key], 'readwrite')
      .objectStore(key);
    const request = objectStore.get(key);
    request.onerror = (event) => {
      // 错误处理！
    };
    request.onsuccess = (event) => {
      console.log('objectStore', objectStore);
      // 把更新过的对象放回数据库。
      const requestUpdate = objectStore.put(newData);
      requestUpdate.onerror = (event) => {
        // 对错误进行处理
      };
      requestUpdate.onsuccess = (event) => {
        // 成功，数据已更新！
        console.log('成功，数据已更新！', event);
      };
    };
  }

  async delData(key) {
    await this.getDb();
    const request =
      this.db.transaction([key], 'readwrite')
        .objectStore(key)
        .delete(key);
    return new Promise((resolve, reject) => {
      request.onsuccess = (event) => {
        // 删除成功！
        console.log('删除成功');
        resolve();
      };
      request.onerror = function(event) {
        console.log('数据删除失败');
        reject(new Error('删除失败'));
      };
    });
  }
}

const indexedDB = new IndexdedDB();
export default indexedDB;

